
from datetime import datetime
import random

import requests

from sign import get_sign

ACCESS_KEY_ID = "hl0qF6jDo81vW3FA"
ACCESS_KEY_SECRET = "66FPuaQOHywXMzMuFCAcaITFwLeUmD"
ECS_URL = "https://ecs.aliyuncs.com/"


def build_params():
    params = {
        "Timestamp": datetime.utcnow().replace(microsecond=0).isoformat()+"Z",
        "Format": "JSON",
        "AccessKeyId": ACCESS_KEY_ID,
        "Action": "DescribeInstances",
        "SignatureMethod": "HMAC-SHA1",
        "SignatureNonce": str(random.random()),
        "Version": "2014-05-26",
        "SignatureVersion": "1.0",
        "RegionId": "cn-shanghai",
    }

    return params


def ecs_api_request(extra_params):
    params = build_params()
    params.update(extra_params)

    signature = get_sign(params, ACCESS_KEY_SECRET)
    params.update({'Signature': signature})

    response = requests.get(ECS_URL, params=params)
    return response.json()


def describe_instances(region_id="cn-shanghai"):
    """Describe Aliyun ECS Instances

    :param region_id: the region id of aliyun ECS service
    :returns: The result in instances
    """

    extra_params = {
        "Action": "DescribeInstances",
        "RegionId": region_id,
    }
    return ecs_api_request(extra_params)


def start_instance(instance_id):
    """Start Aliyun ECS Instance

    :param instance_id: the instance id of aliyun ECS service
    :returns: RequestId
    """
    extra_params = {
        "Action": "StartInstance",
        "InstanceId": instance_id,
    }
    return ecs_api_request(extra_params)


def stop_instance(instance_id, force_stop="false"):
    """Stop Aliyun ECS Instance

    :param instance_id: the instance id of aliyun ECS service
    :returns: RequestId
    """

    extra_params = {
        "Action": "StopInstance",
        "InstanceId": instance_id,
        "ForceStop": force_stop,
    }
    return ecs_api_request(extra_params)


if __name__ == "__main__":
    print(describe_instances(region_id="cn-shanghai"))
